#include "deadProxyGameServer.h"

//Needs to be added to config
int gPort = 7331;
//End Config
void * GameServer::Entry()
{

    SOCKET serverSock;
    SOCKET listenSock;
    //WORD sockVersion;
    //WSADATA wsaData;
    int nret;
    //sockVersion = MAKEWORD(1, 1); // We'd like Winsock version 1.1
    // We begin by initializing Winsock
    //WSAStartup(sockVersion, &wsaData);

    GameThread * gThread;
    // Next, create the listening socket
    listenSock = socket(AF_INET, // Go over TCP/IP
                             SOCK_STREAM,    // This is a stream-oriented socket
                             IPPROTO_TCP); // Use TCP rather than UDP
    if (listenSock == INVALID_SOCKET)
    {
        nret = WSAGetLastError(); // Get a more detailed error
        //ReportError(nret, "socket()"); // Report the error with our custom function
        WSACleanup(); // Shutdown Winsock
        return NULL; // Return an error value
    }
    // Use a SOCKADDR_IN struct to fill in address information
    SOCKADDR_IN serverInfo;
    serverInfo.sin_family = AF_INET;
    serverInfo.sin_addr.s_addr = INADDR_ANY; // Since this socket is listening for connections, any local address will do
    serverInfo.sin_port = htons(gPort); // Convert integer 8888 to network-byte order and insert into the port field

    // Bind the socket to our local server address
    nret = bind(listenSock, (LPSOCKADDR)&serverInfo, sizeof(struct sockaddr));
    if (nret == SOCKET_ERROR)
    {
        nret = WSAGetLastError();
        //ReportError(nret, "bind()");
        WSACleanup();
        return NULL;
    }
    // Make the socket listen
    nret = listen(listenSock, 10); // Up to 10 connections may wait at any
    // one time to be accept()'ed
    if (nret == SOCKET_ERROR)
    {
        nret = WSAGetLastError();
        //ReportError(nret, "listen()");
        WSACleanup();
        return NULL;
    }

    do
    {
        // Wait for a client
        serverSock = accept(listenSock,
                           NULL, // Address of a sockaddr structure (see explanation below)
                           NULL); // Address of a variable containing size of sockaddr struct
        if (serverSock == INVALID_SOCKET)
        {
            nret = WSAGetLastError();
            //ReportError(nret, "accept()");
            WSACleanup();
            return NULL;
        }
        gThread = new GameThread(serverSock);
        gThread->Create();
        gThread->Run();
    } while(true);
    return NULL;
}

void GameServer::OnExit()
{
}
